package com.whf.Controller;

import com.whf.dataobject.ProductCategory;
import com.whf.dataobject.ProductInfo;
import com.whf.enums.ResultEnum;
import com.whf.exception.SellException;
import com.whf.form.ProductForm;
import com.whf.service.CategoryService;
import com.whf.service.ProductService;
import com.whf.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/7/17 0017.
 */
@Controller
@RequestMapping("/seller/product")
@Slf4j
public class SellerProductController {
    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;

    //商品列表
    @GetMapping("/list")
    public ModelAndView list(@RequestParam(value = "page", defaultValue = "1") Integer page,
                             @RequestParam(value = "size", defaultValue = "10") Integer size,
                             Map<String, Object> map) {
        PageRequest request = new PageRequest(page - 1, size);

        try {
            Page<ProductInfo> productInfoPage = productService.findAll(request);
            map.put("currentPage", page);
            map.put("productInfoPage", productInfoPage);
            return new ModelAndView("/product/list", map);
        } catch (SellException e) {
            log.error("[卖家端查询商品列表] 查询商品列表失败,e={}", e.getMessage());
            throw new SellException(ResultEnum.FAIL_PRODUCT_LIST);
        }

    }

    //下架商品
    @GetMapping("/down")
    public ModelAndView down(@RequestParam("productId") String productId,
                             Map<String, Object> map) {

        try {
            ProductInfo productInfo = productService.downSave(productId);
            if (productInfo.getProductStatus() != 1) {
                throw new SellException(ResultEnum.ERROR_PRODUCT_STATUS);
            }
        } catch (SellException e) {
            log.info("[下架商品] 下架商品失败,producrId={}", productId);
            map.put("msg", e.getMessage());
            map.put("url", "/sell/seller/product/list");
            return new ModelAndView("common/error", map);

        }
        map.put("msg", ResultEnum.SUCCESS_PRODUCT_STATUS);
        map.put("url", "/sell/seller/product/list");
        return new ModelAndView("common/success", map);
    }

    //上架商品
    @GetMapping("/up")
    public ModelAndView up(@RequestParam("productId") String productId,
                           Map<String, Object> map) {
        try {
            ProductInfo productInfo = productService.upSave(productId);
            if (productInfo.getProductStatus() != 0) {
                throw new SellException(ResultEnum.ERROR_PRODUCT_STATUS);
            }
        } catch (SellException e) {
            log.info("[上架商品] 上架商品失败,producrId={}", productId);
            map.put("msg", e.getMessage());
            map.put("url", "/sell/seller/product/list");
            return new ModelAndView("common/error", map);

        }
        map.put("msg", ResultEnum.SUCCESS_PRODUCT_STATUS);
        map.put("url", "/sell/seller/product/list");
        return new ModelAndView("common/success", map);
    }

    //新增/修改商品
    @GetMapping("/index")
    public ModelAndView index(@RequestParam(value = "productId", required = false) String productId,
                              Map<String, Object> map) {
        if (!StringUtils.isEmpty(productId)) {
            ProductInfo productInfo = productService.findOneByProductId(productId);
            map.put("productInfo", productInfo);
        }
        List<ProductCategory> productCategoryList = categoryService.findAll();
        map.put("productCategoryList", productCategoryList);
        return new ModelAndView("/product/index", map);
    }

    //保存修改商品
    @PostMapping("/save")
    //每次访问的时候执行方法内的内容,然后把返回的内容放入redis中去,如果返回值和要存储的内容不一样时,使用第二个注解
//    @CachePut(cacheNames = "product", key="123")
    //该注解在改方法被访问后就会清除redis中的缓存,这样再此访问list时就会直接访问数据库重新缓存
    @CacheEvict(cacheNames = "product",key="123")
    public ModelAndView save(@Valid ProductForm productForm,
                             BindingResult bindingResult,
                             Map<String, Object> map) {
        if (bindingResult.hasErrors()) {
            map.put("msg", bindingResult.getFieldError().getDefaultMessage());
            map.put("url", "/sell/seller/product/index?productId=" + productForm.getProductId());
            return new ModelAndView("common/error", map);
        }
        try {
            ProductInfo productInfo =new ProductInfo();
            //根据传递过来的表格数据中是否有商品id,判断是新增商品还是修改商品
            if(!StringUtils.isEmpty(productForm.getProductId())){
                //有商品id,是修改商品,从数据库中查询商品信息,而不是直接new,这样可以保证创建时间不会发生变化
                productInfo = productService.findOneByProductId(productForm.getProductId());
            }else {
                //没有商品id,说明是新增 商品,需要设置商品id
                productForm.setProductId(KeyUtil.uniqueKey());
            }
             BeanUtils.copyProperties(productForm, productInfo);
            productService.save(productInfo);
        } catch (SellException e) {
            map.put("msg", e.getMessage());
            map.put("url", "/sell/seller/product/index?productId=" + productForm.getProductId());
            return new ModelAndView("common/error", map);
        }
        map.put("msg", ResultEnum.SUCCESS_PRODUCT_SAVE);
        map.put("url", "/sell/seller/product/list");
        return new ModelAndView("common/success", map);

    }

}
